package com.core.filter;

import com.alibaba.fastjson.JSON;
import com.core.constant.CharSetConstant;
import com.core.constant.RedisKey;
import com.core.dto.UserDetailsDto;
import com.core.dto.UserInfoDto;
import com.core.service.UsersService;
import com.core.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author : HUANG
 * @create : 2025/6/1 16:51
 * @function :
 */
@Component
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private UsersService usersService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            // 获取请求头中的token
            String token = request.getHeader("Authorization");
            if (token != null && !token.isEmpty()) {
                try {
                    // 解析token
                    Claims claims = JwtUtil.parseJWT(token);
                    String username = claims.getSubject();

                    // 从Redis中获取用户信息
                    ValueOperations<String, String> redisOps = redisTemplate.opsForValue();
                    String userJson = redisOps.get(RedisKey.LOGIN_KEY + username);

                    if (userJson != null) {
                        UserInfoDto user = JSON.parseObject(userJson, UserInfoDto.class);
                        UserDetailsDto userDetailsDto = new UserDetailsDto(user);

                        // 创建认证对象
                        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                                userDetailsDto,
                                null,
                                userDetailsDto.getAuthorities());

                        // 设置认证信息到上下文
                        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                    }
                } catch (ExpiredJwtException e) {
                    log.error("Token已过期: {}", e.getMessage());
                    response.setCharacterEncoding(CharSetConstant.CHAR_SET);
                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    response.getWriter().write("Token已过期");
                    return;
                } catch (Exception e) {
                    log.error("Token解析失败: {}", e.getMessage());
                    response.setCharacterEncoding(CharSetConstant.CHAR_SET);
                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    response.getWriter().write("Token无效");
                    return;
                }
            }

            // 继续过滤器链
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            log.error("认证失败: {}", e.getMessage(), e);
            response.setCharacterEncoding(CharSetConstant.CHAR_SET);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("服务器认证失败");
        }
    }
}
